<template>
  <div class="common-layout">
    <el-container>
      <el-header class="customer-header">
        <el-button @click="logic.isOpen = true" type="primary">新增角色</el-button>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <el-button @click="logic.deptOpen = true" type="primary">部门新增</el-button>
      </el-header>
      <el-main>
        <el-table :data="userquery" border style="width: 100%">
          <el-table-column prop="user_Account" label="用户名"></el-table-column>
          <el-table-column prop="user_NickName" label="昵称"></el-table-column>
          <el-table-column prop="user_Email" label="邮箱"></el-table-column>
          <el-table-column prop="user_Phone" label="手机号码"></el-table-column>
          <el-table-column prop="dept_Name" label="部门"></el-table-column>
          <el-table-column prop="role_Name" label="角色"></el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <!--@vue-ignore-->
              <el-button @click="handleEdit(scope.$index, scope.row)" type="warning">编辑</el-button>
              <!--@vue-ignore-->
              <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--分页-->
        <table style="margin-top: 10px;">
          <tr>
            <td>
              <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                :page-sizes="[10, 15, 20]" :background="true" layout="slot" :total="page.totalCount">
                <span style="color: blue;">当前&nbsp;<span>{{ page.pageIndex }}</span>&nbsp;\&nbsp;<span>{{ page.totalPage
                }}</span>&nbsp;页</span>
              </el-pagination>
            </td>
            <td>
              <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                :page-sizes="[10, 15, 20]" :background="true" layout="total,sizes,slot, prev, pager"
                :total="page.totalCount" prev-text="上一页">
                <el-button style="margin-left: 10px;margin-right: -5px;" class="btn-prev"
                  :disabled="page.pageIndex == 1" @click="page.pageIndex = 1">首页</el-button>
              </el-pagination>
            </td>
            <td>
              <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                :page-sizes="[10, 15, 20]" :background="true" layout="  next,slot,jumper" :total="page.totalCount"
                next-text="下一页">
                <el-button style="margin-left: 8px;" class="btn-next" :disabled="page.pageIndex == page.totalPage"
                  @click="page.pageIndex = page.totalPage">尾页</el-button>
              </el-pagination>
            </td>
          </tr>
        </table>
      </el-main>
    </el-container>
<!--新增角色弹窗-->
<el-dialog v-model="logic.isOpen" title="角色新增" width="500">
    <el-form :model="form">
      <!--@vue-ignore-->
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="form.role_Name" autocomplete="off" />
      </el-form-item>
      <!--@vue-ignore-->
      <el-form-item label="父级编号" :label-width="formLabelWidth">
        <el-tree ref="treeRef" style="max-width: 600px" :data="data" show-checkbox default-expand-all node-key="id"
          highlight-current :props="defaultProps" />
      </el-form-item>
      <!--@vue-ignore-->
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input :readonly="true" v-model="logic.remark" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.isOpen = false">取消</el-button>
        <el-button type="primary" @click="InsertRole">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增部门弹窗 -->
  <el-dialog v-model="logic.deptOpen" title="部门新增" width="800">
    <el-table :data="deptForm" border>
      <!-- 序号列 -->
      <el-table-column type="index" label="序号" width="55" />

      <!-- 部门名称 -->
      <el-table-column prop="dept_Name" label="部门名称">
        <template #default="scope">
          <el-input v-model="scope.row.dept_Name" placeholder="请输入部门名称" />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="success" @click="addRow">新增行</el-button>
          <el-button type="danger" @click="deleteRow(scope.$index)">
            删除行
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-button style="margin-top: 10px; margin-left: 10px;" type="primary" @click="confirmAddition">
      确定保存
    </el-button>
  </el-dialog>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
  children: 'children',
  label: 'label',
  url: 'url'
}

//级联对象
const data = ref([])

const QueryRoleCascader = () => {
  axios.get("http://localhost:5115/api/RBAC/GetURCascader/GetURCascaderAsync")
    .then(res => {
      //console.log(res);
      if (res.data.code == 200) {
        data.value = res.data.data
      }
    })
}

const logic = reactive({
  isOpen: false,
  deptOpen: false,
  remark: "如果需要单独新建一个新的父级角色则父级编号不选!"
})
//const formLabelWidth = '140px'

const form = reactive({
  role_Name: '',
  role_ParentId: '',
})
function InsertRole() {
  form.role_ParentId = treeRef.value!.getCheckedKeys(false).toString();
  //如果不选则表示新增个一级角色
  if (form.role_ParentId.length == 0) {
    form.role_ParentId = "0";
  }
  else {
    //否则取第一个父级 
    let result = form.role_ParentId.split(",")[0];
    form.role_ParentId = result;
  }
  axios.post("http://localhost:5259/api/Role/InsertRole/InsertRoleAsync", form)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success("新增角色成功");
        logic.isOpen = false
      }
      else {
        ElMessage.error(res.data.message);
        return;
      }
    })
}

// 表单数据
const deptForm = reactive([
  {
    dept_Name: "", // 部门名称（默认空）
  },
]);

// 新增一行
const addRow = () => {
  deptForm.push({ dept_Name: "" }); // 添加空行
};

// 删除指定行
const deleteRow = (index: number) => {
  if (deptForm.length > 1) {
    deptForm.splice(index, 1); // 移除指定行
  } else {
    ElMessage.warning("至少保留一行表单！");
  }
};

// 确认保存
const confirmAddition = () => {
  const deptNamesString = deptForm.map((item) => item.dept_Name).join(',');
  console.log("最终表单数据：", deptNamesString);
  // 在这里处理保存逻辑，例如提交到后端
  let data = reactive({
    dept_Name: deptNamesString
  })
  axios.post("http://localhost:5259/api/Dept/CreateDept", data)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success("新增成功");
        logic.deptOpen = false;
      }
      else {
        ElMessage.error("新增失败");
        return;
      }
    })
};

//分页信息
const page = reactive({
  totalCount: 0,
  totalPage: 0,
  pageIndex: 1,
  pageSize: 10,
})
//监听分页信息变化
watch(page, () => {
  getuser();
})

//查询条件
const userinfo = reactive({
  user_Name: '',
  role_Name: '',
  dept_Name: '',
})

const userquery = ref([])
const getuser = () => {
  axios.get('http://localhost:5115/api/User/UserRoleQuery', {
    params: {
      pageIndex: page.pageIndex,
      pageSize: page.pageSize,
      user_Name: userinfo.user_Name,
      role_Name: userinfo.role_Name,
      dept_Name: userinfo.dept_Name
    }
  })
    .then(res => {
      console.log(res);
      userquery.value = res.data.data.data
      page.totalCount = res.data.data.totalCount
      page.totalPage = res.data.data.totalPage
    })
}

onMounted(() => {
  getuser()
  QueryRoleCascader();
})
</script>

<style scoped>
/* 添加一些样式，如果需要的话 */
.customer-header {
  background-color: transparent;
  /* 将头部背景设为透明 */
}
</style>